//获取元素
var leftimg = document.querySelector(".left"); //左侧图片
var rightimg = document.querySelector(".right"); //右侧放大镜图片
var dots = document.querySelectorAll(".dots li"); //缩略图
var mask = document.querySelector(".mask"); //遮罩层
//背景图片数组
var bgs = ["url('images/imgA_2.jpg')", "url('images/imgB_2.jpg')", "url('images/imgC_2.jpg')"];
var bigbgs = ["url('images/imgA_3.jpg')", "url('images/imgB_3.jpg')", "url('images/imgC_3.jpg')"];



//初始化
function init() {
    //为缩略图绑定点击事件
    for (var i = 0; i < dots.length; i++) {
        //初始化数据
        (function (i) {
            dots[i].onclick = function () {
                var checked = document.querySelector(".dots li.check");
                if (checked) checked.className = "";
                this.className = "check";
                leftimg.style.backgroundImage = bgs[i];
                rightimg.style.backgroundImage = bigbgs[i];

            }
        })(i);
    }
}

//绑定函数
function bindEvent() {
    //为在左侧图片鼠标移入绑定事件
    leftimg.onmouseenter = function (e) {

        //显示遮罩层
        mask.style.opacity = 1;
        //显示放大镜区域的图片
        rightimg.style.opacity = 1;


        //绑定遮罩层移动事件
        leftimg.addEventListener("mousemove", function (e) {
            //获取左侧图片的所有属性
            var leftimgprop = leftimg.getBoundingClientRect();
            //获取遮罩层的所有属性，隐藏时获取不到
            var maskprop = mask.getBoundingClientRect();
            //计算遮罩层可移动的最大值与最小值
            var maxwidth = leftimgprop.width - maskprop.width;
            var maxheight = leftimgprop.height - maskprop.height;
            var left = e.clientX - leftimgprop.left - maskprop.width / 2;
            var top = e.clientY - leftimgprop.top - maskprop.height / 2;
            //遮罩层移动范围限制
            if (left < 0) left = 0;
            if (left > maxwidth) left = maxwidth;
            if (top < 0) top = 0;
            if (top > maxheight) top = maxheight;
            mask.style.left = left + "px";
            mask.style.top = top + "px";


            //放大镜区域
            //获取比例
            // var x = leftimgprop.width / glassprop.width;
            // var y = leftimgprop.height / glassprop.height;
            //移动背景位置
            var left = parseInt(mask.style.left) * -1 + "px";
            var top = parseInt(mask.style.top) * -1 + "px";
            rightimg.style.backgroundPosition = left + " " + top;
        })



    }
    //给左侧图片绑定鼠标移出事件
    leftimg.onmouseleave = function () {
        mask.style.opacity = 0;
        leftimg.onmousemove = null;
        //隐藏放大镜区域
        rightimg.style.opacity = 0;
    }
}

//一键启动
function main() {
    init();
    bindEvent();
}
main();